import React, { useState, createContext, useContext } from 'react';
import { Snackbar, Alert } from '@mui/material';

// 创建 Snackbar 上下文
const SnackbarContext = createContext();

// 自定义 Snackbar 提供者
export const SnackbarProvider = ({ children }) => {
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const [snackbarSeverity, setSnackbarSeverity] = useState('info');

    const handleSnackbarClose = () => {
        setSnackbarOpen(false);
    };

    const openSnackbar = (message, severity = 'info') => {
        setSnackbarMessage(message);
        setSnackbarSeverity(severity);
        setSnackbarOpen(true);
    };

    return (
        <SnackbarContext.Provider value={openSnackbar}>
            {children}
            <Snackbar
                open={snackbarOpen}
                autoHideDuration={4000}
                onClose={handleSnackbarClose}
                anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
            >
                <Alert onClose={handleSnackbarClose} severity={snackbarSeverity} sx={{ width: '100%' }}>
                    {snackbarMessage}
                </Alert>
            </Snackbar>
        </SnackbarContext.Provider>
    );
};

// 自定义的 hook 来使用 Snackbar
export const useSnackbar = () => {
    return useContext(SnackbarContext);
};
